package com.myBlog.intercaptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.myBlog.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            this.sendJsonMessage(response,"token不能为空");
        }
        try {
            JwtUtil.validateToken(token);
        } catch (SignatureVerificationException e) {
            log.error("无效签名！ 错误 ->", e);
            this.sendJsonMessage(response,"无效签名！ 错误");
            return false;
        } catch (TokenExpiredException e) {
            log.error("token过期！ 错误 ->", e);
            this.sendJsonMessage(response,"token过期！ 错误 ->");
            return false;
        } catch (AlgorithmMismatchException e) {
            log.error("token算法不一致！ 错误 ->", e);
            this.sendJsonMessage(response,"token算法不一致！ 错误 ->");
            return false;
        } catch (Exception e) {
            log.error("token无效！ 错误 ->", e);
            this.sendJsonMessage(response,"token无效！ 错误 ->");
            return false;
        }
        return true;
    }

    /**
     * 响应json数据给前端
     *
     * @param response
     * @param obj
     */
    public void sendJsonMessage(HttpServletResponse response, Object obj) {
        // response的头信息
        response.setContentType("application/json;charset=utf-8");
        try (PrintWriter writer = response.getWriter();){
            writer.print(obj);
            response.flushBuffer();
        } catch (IOException e) {
            log.error("响应json数据给前端异常:{}",e);
        }
    }

}
